"""演示等额本息还款计划的计算公式"""
import math
import common_def
import date_utils
from datetime import datetime, date


def equal_loan_pay(amount, day_rate, charge_rate, term, beg_interest):
    """
    等额本息还款方式，计算规则：
    1、计算出每期的期供金额
    2、依次计算每期的应还利息、应还本金
    3、计算最后一期的应还本金、应还利息
    :param amount:
    :param day_rate:
    :param charge_rate:
    :param term:
    :param beg_interest:
    :return:
    """
    print("---------进入方法---------")
    # 定义还款计划
    repay_lst = []
    m_rate = day_rate * common_def.base_term / 12
    term_amount = round(
        amount * ((m_rate * math.pow(1 + m_rate, term)) / (math.pow(1 + m_rate, term) - 1)), 2)  # 计算每期的期供金额
    print("开始计算期供金额，期供金额为：", term_amount)
    remain_principal = amount  # 期初剩余本金等于借款本金
    period_interest_date = beg_interest
    # 计算每期的具体还款计划
    for i in range(term):
        period_end_date = date_utils.date_add(period_interest_date, 1, datetime.month)  # 当期还款日期
        period_interest_days = date_utils.date_diff(period_interest_date, period_end_date)  # 当期实际计息天数
        if i < term - 1:
            period_interest = round(remain_principal * day_rate * period_interest_days, 2)  # 当期应还利息
            period_principal = term_amount - period_interest  # 应还本金
        else:
            period_principal = remain_principal  # 最后一期应还本金等于剩余本金
            period_interest = round(remain_principal * day_rate * period_interest_days, 2)  # 当期应还利息

        period_fee = round(amount * charge_rate, 2)  # 本期费用
        period_amount = period_principal + period_interest + period_fee  # 期供金额
        remain_principal = remain_principal - period_principal  # 剩余本金
        repay_item = dict()
        repay_item["index"] = (i + 1)
        repay_item["beg_interest"] = date_utils.format_date(period_interest_date, "%Y-%m-%d")  # 起息日期
        repay_item["interest_days"] = period_interest_days  # 计息天数
        repay_item["end_date"] = date_utils.format_date(period_end_date, "%Y-%m-%d")  # 还款日期
        repay_item["amount"] = period_principal  # 应还本金
        repay_item["interest"] = period_interest  # 应还利息
        repay_item["total_fee"] = period_fee  # 应还费用
        repay_item["total_amount"] = period_amount  # 期供金额
        repay_item["remain_amount"] = remain_principal  # 剩余本金
        repay_lst.append(repay_item)
        period_interest_date = date_utils.date_add(period_end_date, 1, datetime.day)

    return repay_lst
